//
// Created by Moonbreeze on 2015/12/18.
//
#include "JavaClass.h"
#include "ClassHeap.h"
#include "FilePathManager.h"

ClassHeap::ClassHeap() {
    pFilePathManager = new FilePathManager();
}

ClassHeap::~ClassHeap() {
    delete pFilePathManager;
}

bool ClassHeap::AddClass(JavaClass *pJavaClass) {
    if (!pJavaClass) return false;
    std::string name = pJavaClass->GetName();
    /*
     * make sure the className is legal
     */
    m_ClassMap.insert(std::make_pair(name,pJavaClass));
    return true;
}

JavaClass* ClassHeap::GetClass(std::string strClassName) {
    std::map<std::string,JavaClass*>::iterator result = m_ClassMap.find(strClassName);
    if(result != m_ClassMap.end()){
        return result->second;
    }else{
        JavaClass* pClass = new JavaClass();
        bool reb = this->LoadClass(strClassName, pClass);
        if (reb == false) {
            delete pClass;
            return NULL;
        }else{
            
            return pClass;
        }
        
    }
}

bool ClassHeap::LoadClass(std::string strClassName, JavaClass *pClass) {
    std::string path,relPath;
    if (!pClass) return false;

    relPath = strClassName;
    /*
     * for now just use relative path,
     * we just replace the "." to "/" so we can use fstream to load
     */
    if(!pFilePathManager->GetAbsolutePath(relPath,path))
        return false;
    path += ".class";
    bool bRet = pClass->LoadClassFormFile(path);
    if (!bRet) return false;

    pClass->SetClassHeap(this);
    return AddClass(pClass);
}